/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.nio.http.server;

import cn.hermit.nio.http.Http;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 29/5/2017
 */
public class HttpRequest implements Http {

    protected Verb verb;
    protected String requestURI;
    protected Version version;

    protected Map<String, String> headerMap = new TreeMap<String, String>();

    protected Map<String, String> queryParameterMap = null;

    protected Map<String, String> formParameterMap = null;

    protected byte[] body;

    public String getRequestURI() {
        return requestURI;
    }

    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    public Verb getVerb() {
        return verb;
    }

    public void setVerb(Verb verb) {
        this.verb = verb;
    }

    public Version getVersion() {
        return version;
    }

    public void setVersion(Version version) {
        this.version = version;
    }

    public Map<String, String> getHeaderMap() {
        return headerMap;
    }

    public String getHeader(String name) {
        return headerMap.get(name);
    }

    public void setHeader(String name, String value) {
        headerMap.put(name, value);
    }

    public String getQueryParameter(String name) {
        int index = requestURI.indexOf('?');
        if (index == -1) {
            return null;
        }
        if (queryParameterMap == null) {
            String paramStr = requestURI.substring(index + 1);
            queryParameterMap = fetchParameters(paramStr);
        }
        return queryParameterMap.get(name);
    }

    public String getFormParameter(String name) {
        if (body == null || body.length == 0) {
            return null;
        }
        if (formParameterMap == null) {
            String paramStr = new String(body);
            formParameterMap = fetchParameters(paramStr);
        }
        return formParameterMap.get(name);
    }

    private Map<String, String> fetchParameters(String paramStr) {
        Map<String, String> queryParameterMap = null;
        String[] paramArr = paramStr.split("&");
        if (paramArr == null || paramArr.length == 0) {
            return null;
        } else {
            queryParameterMap = new LinkedHashMap<>();
            for (String param : paramArr) {
                param = param.trim();
                String[] pair = param.split("=");
                if (pair == null || pair.length == 0) {
                    continue;
                }
                queryParameterMap.put(pair[0], pair.length > 1 ? pair[1] : null);
            }
        }
        return queryParameterMap;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }
}
